<template>
  <!-- 登录页单独渲染 -->
  <div v-if="isLoginPage">
    <router-view />
  </div>
  <!-- 后台主布局 -->
  <div v-else class="admin-layout">
    <AdminSidebar :menu-groups="menuGroups" :active-key="activeMenuKey" />
    <div class="main-content">
      <AdminHeader :title="pageTitle" :user="user" />
      <router-view />
    </div>
  </div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import AdminSidebar from '@/components/admin/AdminSidebar.vue'
import AdminHeader from '@/components/admin/AdminHeader.vue'
import { useAppStore } from '@/stores/appStore'
import routes from '@/router/routes'

const router = useRouter()
const route = useRoute()
const appStore = useAppStore()

function generateMenu(routes, basePath = '/admin') {
  return routes
    .filter(r => r.meta && r.meta.title && !(typeof r.path === 'string' && r.path.startsWith(':')))
    .map(r => {
      const path = r.path ? (r.path.startsWith('/') ? r.path : basePath + (basePath.endsWith('/') ? '' : '/') + r.path) : basePath
      if (r.children && r.children.length) {
        // 一级菜单（分组）
        return {
          key: r.meta.title,
          label: r.meta.title,
          icon: r.meta.icon || 'fas fa-folder',
          children: generateMenu(r.children, path)
        }
      } else {
        // 二级菜单
        return {
          key: r.name,
          label: r.meta.title,
          icon: r.meta.icon || 'fas fa-angle-right',
          path: path
        }
      }
    })
}

const adminRoute = routes.find(r => r.path === '/admin')
const menuGroups = computed(() => generateMenu(adminRoute && adminRoute.children ? adminRoute.children : []))

const activeMenuKey = computed(() => route.name ? String(route.name) : '')
const pageTitle = computed(() => typeof route.meta?.title === 'string' ? route.meta.title : '控制面板')
const isLoginPage = computed(() => route.path === '/admin/login')
const user = computed(() => appStore.user)

// 登录守卫
if (route.path.startsWith('/admin') && route.path !== '/admin/login' && !appStore.user.isLoggedIn) {
  router.replace('/admin/login')
}
</script>
<style scoped>
.admin-layout {
  display: flex;
  min-height: 100vh;
  background: #f0f4f8;
}
.main-content {
  flex: 1;
  margin-left: 260px;
  padding: 20px;
  overflow-y: auto;
  height: 100vh;
  padding-top: 80px;
}
</style>